import { useAsyncEffect } from '@gnlab/utils/env-react'
import { Spin, message, Modal, Table, Select, DatePicker } from 'antd'
import type { Dayjs } from 'dayjs'
import  defaultAvatar  from '@/desktop/assets/avatar.jpg'
import services from '@/services'
import type {
  BatchApplyConfig,
  BatchApplyTask,
  BatchApplyConfigQywx,
} from '@/services/features/group-batch-apply'
import { BatchApplyTaskStatus } from '@/services/features/group-batch-apply'
import ApplyRecordsModal from './ApplyRecords'
import './index.module.less'

export default function ConfigTasksModal(props: {
  config?: BatchApplyConfig
  onClose: () => void
}) {
  const { config, onClose } = props

  return <Modal
    styleName="modal"
    title={config ? `${config.name} 明细数据` : ''}
    footer={null}
    width="1000px"
    open={!!config}
    onCancel={onClose}
    maskClosable
    destroyOnClose
  >
    {config ? <Content config={config} /> : null}
  </Modal>
}

function Content(props: { config: BatchApplyConfig }) {
  const { config } = props

  const [qywxs, setQywxs] = useState<Map<string, BatchApplyConfigQywx>>(new Map()) // 此配置下的企业微信信息
  const [tasks, setTasks] = useState<BatchApplyTask[] | null>(null)
  const [timeRange, setTimeRange] = useState<null | [Dayjs | null, Dayjs | null]>([null, null])
  const loadTasks = useCallback(async () => {
    const times =
      timeRange && timeRange[0] !== null && timeRange[1] !== null
        ? (timeRange as [Dayjs, Dayjs])
        : undefined
    const res = await services.features.groupBatchApply.loadTasks(config.id, times)
    if (!res.success) return void message.warning(`任务详情获取失败：${res.error}`)
    setTasks(res.data)
  }, [config, timeRange])
  useEffect(() => {
    void loadTasks()
  }, [loadTasks])

  useAsyncEffect(async () => {
    const res = await services.features.groupBatchApply.getQywxListForConfig(config.id)
    if (res.success) setQywxs(new Map(res.data.map(qywx => [qywx.wxid, qywx])))
    else void message.warning('获取企业微信列表失败')
  }, [config])

  const accountNames = useMemo(
    () => [...new Set([...qywxs.values()].map(qywx => qywx.accountName))],
    [qywxs],
  )

  const [filterAccount, setFilterAccount] = useState('')
  const filteredTasks = useMemo(() => {
    if (!tasks) return null
    if (!filterAccount) return tasks
    return tasks.filter(task => {
      const accountName = qywxs.get(task.wxid)?.accountName
      return accountName === filterAccount
    })
  }, [tasks, filterAccount, qywxs])

  const [showingRecords, setShowingRecords] = useState<{ taskId: number; qywxName: string } | null>(
    null,
  ) // 要显示加人记录的 task 信息

  const renderQywx = useCallback(
    (task: BatchApplyTask) => {
      const qywx = qywxs.get(task.wxid)
      if (!qywx) return null
      return <div styleName="qywx-info">
        <img src={qywx.avatar || defaultAvatar} />
        <div styleName="info-main">
          <div styleName="name">{qywx.friendlyName}</div>
          <div styleName="corp">{qywx.corpname}</div>
        </div>
      </div>
    },
    [qywxs],
  )

  const renderAccount = useCallback(
    (task: BatchApplyTask) => {
      const qywx = qywxs.get(task.wxid)
      return qywx ? qywx.accountName : ''
    },
    [qywxs],
  )

  const renderStatus = useCallback((task: BatchApplyTask) => {
    const map = new Map([
      [BatchApplyTaskStatus.Normal, '正常'],
      [BatchApplyTaskStatus.Exceed, '过频停止'],
      [BatchApplyTaskStatus.Limited, '到达设置上限'],
    ])
    return map.get(task.status)!
  }, [])

  const renderPassedRate = useCallback((task: BatchApplyTask) => {
    if (!task.applyedCount) return '' // 一次都没申请过，没有通过率的概念
    const rate = Math.round((task.passedCount / task.applyedCount) * 100 * 10) / 10
    return `${rate}%`
  }, [])

  const renderActions = useCallback(
    (task: BatchApplyTask) => {
      const qywx = qywxs.get(task.wxid)
      if (!qywx) return null
      const show = () => setShowingRecords({ taskId: task.id, qywxName: qywx.friendlyName })
      return <a onClick={show}>明细</a>
    },
    [qywxs],
  )

  return <div>
    <div styleName="search">
      <label>
        <span>时间：</span>
        <DatePicker.RangePicker showTime value={timeRange} onChange={setTimeRange} />
      </label>
      <label>
        <span>所属员工：</span>
        <Select value={filterAccount} onChange={setFilterAccount}>
          <Select.Option value="">请选择</Select.Option>
          {accountNames.map(name => <Select.Option key={name} value={name}>
            {name}
          </Select.Option>)}
        </Select>
      </label>
    </div>

    {!filteredTasks ? (
      <div styleName="loading">
        <Spin tip="加载中..." size="large" />
      </div>
    ) : null}

    {filteredTasks ? (
      <div styleName="qywxs">
        <Table<BatchApplyTask>
          rowKey="wxid"
          dataSource={filteredTasks}
          scroll={{ y: 500 }}
          pagination={false}
        >
          <Table.Column<BatchApplyTask> title="企微账号" width={200} render={renderQywx} />
          <Table.Column<BatchApplyTask> title="所属员工" width={120} render={renderAccount} />
          <Table.Column<BatchApplyTask> title="状态" width={120} render={renderStatus} />
          <Table.Column<BatchApplyTask>
            title="已发送"
            dataIndex="applyedCount"
            width={80}
            align="center"
          />
          <Table.Column<BatchApplyTask>
            title="已通过"
            dataIndex="passedCount"
            width={80}
            align="center"
          />
          <Table.Column<BatchApplyTask>
            title="通过率"
            width={80}
            render={renderPassedRate}
            align="center"
          />
          <Table.Column<BatchApplyTask> title="查看" width={90} render={renderActions} />
        </Table>
      </div>
    ) : null}

    <ApplyRecordsModal taskInfo={showingRecords} onClose={() => setShowingRecords(null)} />
  </div>
}
